<?php
namespace app\admin\controller;
use app\admin\model\News as Mod;
// use app\home\model\User as UserModel;
use app\admin\model\NewsImage as NewsImageModel;
use app\admin\validate\News as NewsValidate;
use think\facade\Request;
use yichenthink\utils\FileBase64;
use yichenthink\utils\ReturnMsg;

class News extends Base {
	// 查询列表
	public function list($p = 0, $n = 10, $category_id = 0, $isTrashed = 0) {
		if ($n % 10 != 0 or $n > 100) {
			$n = 100;
		}
		// 查找页数
		$startNum = $n * $p;
		$message = '';
		$data = [];
		$map = [];
		if (is_numeric($category_id) && $category_id != 0) {
			$map[] = ['category_id', '=', $category_id];
		}
		$Mod = new Mod;
		// 查询被删除的
		if ($isTrashed == 1) {
			$data = $Mod::onlyTrashed()->with(['newsContent' => function ($query) {
				$query->field(['image', 'title', 't_id', 'content']);
			}])->where($map)->field(['create_time', 'update_time', 'delete_time', 'id', 'state', 'category_id'])->hidden(['content'])->limit($startNum, $n)->select();

		} else {
			$data = $Mod::with(['news_content' => function ($query) {
				$query->field(['image', 'title', 't_id', 'content']);
			}])->where($map)->field(['create_time', 'update_time', 'delete_time', 'id', 'state', 'category_id'])->hidden(['content'])->limit($startNum, $n)->select();
		}

		ReturnMsg::returnMsg(200, $message, $data);
	}

	//查询详情
	public function detail($id = '0', $isTrashed = 0) {
		$message = '没有数据';
		$code = 400;

		$message = '';
		$data = [];
		$map = [];
		$map[] = ['id', '=', $id];

		$Mod = new Mod;
		// 查询被删除的
		if ($isTrashed == 1) {
			$data = $Mod::onlyTrashed()->with(['newsContent' => function ($query) {
				$query->field(['content', 'image', 'title', 't_id']);
			}, 'newsImage' => function ($query) {
				$query->field(['suffix', 'src', 't_id']);
			}])->where($map)->field(['create_time', 'update_time', 'delete_time', 'id', 'state', 'category_id'])->find();

		} else {
			$data = $Mod::with(['newsContent' => function ($query) {
				$query->field(['content', 'image', 'title', 't_id']);
			}, 'newsImage' => function ($query) {
				$query->field(['suffix', 'src', 'id', 't_id']);
			}])->where($map)->field(['create_time', 'update_time', 'delete_time', 'id', 'state', 'category_id'])->find();
		}

		ReturnMsg::returnMsg(200, $message, $data);
	}
	public function add($form) {
		//设置允许修改的字段
		$message = '';
		$code = 400;
		$map = [];
		// ReturnMsg::returnMsg($code, $message, $form);
		$map[] = ['user_id', '=', $this->userInfo['uid']];
		// 过滤数组中的安全字段
		$safe = [
			'state' => 'state',
			'user_id' => 'user_id',
			'category_id' => 'category_id',
			'content' => 'content',
			'title' => 'title',
		];
		$validate = new NewsValidate;

		if (!$validate->scene('add')->check($form)) {
			// dump($validate->getError());
			ReturnMsg::returnMsg($code, $validate->getError(), $form);
		}
		$form['user_id'] = $this->userInfo['uid'];
		$Mod = new Mod;

		foreach ($form as $key => $value) {
			if (isset($safe[$key])) {
				$key = $safe[$key];
				$Mod->$key = $value;
			}
		}
		$imageArr = $form['image'];

		$form['image'] = $imageArr[0];
		$FileBase64 = new FileBase64;
		$imageData = [];
		//获取base64流的信息
		if ($FileBase64->getBase64Info($form['image'])) {
			// 预备上传 返回图片上传后的信息 路径名 图片类型，尺寸等信息
			$FileBase64->readyUpload('news/' . date('y/m/d/'));
			$FileBase64->url = $FileBase64->url;
			//获取图片地址
			$Mod->image = $FileBase64->url;

		};

		if ($Mod->together([
			'newsContent' => [
				'image',
				'title',
				'content'],
		])->save()) {
			//开始上传
			if (!$FileBase64->upload()) {
				$message = '发布成功，但图片上传失败';
			} else {
				// 附件图片表将要存入详细信息主图
				$imageData = [
					't_id' => $Mod->id,
					'suffix' => $FileBase64->suffix,
					'src' => $FileBase64->url,
					'user_id' => $Mod->user_id,
					'size' => $FileBase64->size,
					'content_type' => $FileBase64->contentType,
					'type' => $FileBase64->type,
				];
				// 详细数据保存到图片表
				$Mod->newsImage()->save($imageData);
			}
			$code = 200;

		}
		// 如果有更多图片 将会继续上传到关联的图片表
		foreach ($imageArr as $key => $value) {
			if ($key != 0 && $FileBase64->getBase64Info($imageArr[$key])) {
				$FileBase64->readyUpload('news/' . date('y/m/d/'));
				$imageData = [
					't_id' => $Mod->id,
					'suffix' => $FileBase64->suffix,
					'src' => $FileBase64->url,
					'user_id' => $Mod->user_id,
					'size' => $FileBase64->size,
					'content_type' => $FileBase64->contentType,
					'type' => $FileBase64->type,
				];
				if ($Mod->newsImage()->save($imageData)) {
					$FileBase64->upload();
				};
			}
		}

		ReturnMsg::returnMsg($code, $message, $Mod);
	}

	public function update($id) {
		$form = $this->param;
		//设置允许修改的字段
		$message = '';
		$code = 400;
		// ReturnMsg::returnMsg($code, $message, $form);
		$map = [["id", '=', $id]];
		// ReturnMsg::returnMsg($code, $message, $form);
		// $map[] = ['user_id', '=', $this->userInfo['uid']];
		// 过滤数组中的安全字段
		$safe = [
			'state' => 'state',
			'category_id' => 'category_id',
		];
		$contentSafe = [
			'content' => 'content',
			'title' => 'title',
			'image' => 'image',
		];
		$validate = new NewsValidate;

		if (!$validate->check($form)) {
			// dump($validate->getError());
			ReturnMsg::returnMsg($code, $validate->getError(), $form);
		}

		$Mod = Mod::where($map)->find();
		// ReturnMsg::returnMsg($code, $message, $Mod);
		if ($Mod) {
			$modData = [];
			$contentData = [];
			foreach ($form as $key => $value) {
				if (isset($safe[$key])) {
					$key = $safe[$key];
					$modData[$key] = $value;
				} elseif (isset($contentSafe[$key])) {
					$key = $contentSafe[$key];
					$contentData[$key] = $value;
				}
			}
			if (count($modData) > 0 && $Mod->save($modData)) {
				$code = 200;
			}

			if (count($contentData) > 0) {
				if ($Mod->newsContent) {
					$Mod->newsContent->save($contentData);
				} else {
					$Mod->newsContent()->save($contentData);
				}
				$code = 200;
			}
		}

		ReturnMsg::returnMsg($code, $message, $Mod);
	}
	// 删除一条
	public function delete($id = 0, $isTrue = false) {
		$map[] = ['id', '=', $id];
		// $map[] = ['user_id', '=', $this->userInfo['uid']];
		$code = 400;
		$Mod = Mod::withTrashed()->where($map)
			->find();
		if ($Mod) {
			if ($isTrue) {
				$isTrue = true;
				// $newsImage = $Mod->newsImage()->withTrashed();
				$newsImage = NewsImageModel::where('t_id', $id)->select();

				$Img = [];
				foreach ($newsImage as $key => $value) {
					if (isset($value->src)) {
						$Img[] = ['t_id', '=', $value->id];
						$FileBase64 = new FileBase64;
						// 删除图片资源
						$FileBase64->destroy($value->src);
					}
				}
				// $newsContent = $Mod->newsContent();
				// 删除关联内容表数据

				if ($Mod->newsContent) {
					$Mod->newsContent->delete();
				}
				// // 删除关联评论表数据
				// $Mod->newsComment()->delete($isTrue);
				// // 删除关联收藏表数据
				// $Mod->newsCollect()->delete($isTrue);

				// 删除图片表数据
				NewsImageModel::where('t_id', $id)->delete();
				// 删除主表数据
				$Mod->delete($isTrue);
				$delete = new \app\home\model\DeleteTable;
				// 过滤数组中的安全字段
				$safe = [
					'state' => 'state',
					'user_id' => 'user_id',
					'category_id' => 'category_id',
					'id' => 't_id',
					'content' => json_encode($Mod),
				];

				$delete->t_id = $Mod->id;
				$delete->model = __CLASS__;
				$delete->func = __FUNCTION__;

				$delete->sql = $Mod->getLastSql();
				$delete->allowField(['sql', 'model', 't_id', 'func', 'content'])->save();

				# code...
			} else {
				$Mod->delete($isTrue);
			}
			if ($Mod) {
				$code = 200;
			}

		}

		ReturnMsg::returnMsg($code, '', $Mod);
	}

	//恢复一条
	public function restore($id = 0) {

		$map = [];
		$map[] = ['id', '=', $id];
		$code = 400;
		$Mod = Mod::onlyTrashed()
			->where($map)
			->find();
		# code...
		if ($Mod) {
			$code = 200;
			$Mod->restore();
		}
		// $user = UserModel::restore($list);
		ReturnMsg::returnMsg($code, '', $Mod);
	}

}
